/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO;

import VO.CPerro;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.swing.JOptionPane;

/**
 *
 * @author Kyosuke
 */
public class CPerroDAO {
    public boolean Insertar(CPerro perro) throws Exception{
    boolean flag = false;
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("EjercicioJPAPU"); 
    EntityManager em = emf.createEntityManager();
    EntityTransaction trans = em.getTransaction();
    
    trans.begin();
    try {
        em.persist(perro);
        trans.commit();
        flag = true;
        
      }catch (Exception ex){
          trans.rollback();
          throw  new Exception("Error en la BD" + ex.getMessage());          
      }finally{
        em.close();
    }
   
    return flag;
    }
        public boolean actualizar(CPerro perro) throws Exception{
    boolean flag = false;
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("EjercicioJPAPU"); 
    EntityManager em = emf.createEntityManager();
    EntityTransaction trans = em.getTransaction();
    
    trans.begin();
    try {
        em.merge(perro);
        trans.commit();
        flag = true;
        
      }catch (Exception ex){
          trans.rollback();
          throw  new Exception("Error en la BD" + ex.getMessage());  
      }finally{
        em.close();
    }
   
    return flag;
    }
            public boolean eliminar(CPerro perro) throws Exception{
    boolean flag = false;
    EntityManagerFactory emf = Persistence.createEntityManagerFactory("EjercicioJPAPU"); 
    EntityManager em = emf.createEntityManager();
    EntityTransaction trans = em.getTransaction();
    
    trans.begin();
    try {
        em.remove(em.merge(perro));
        trans.commit();
        flag = true;
        
      }catch (Exception ex){
          trans.rollback();
          throw  new Exception("Error en la BD" + ex.getMessage());  
      }finally{
        em.close();
    } 
    return flag;
    }
            
            public CPerro getPerroByID(int codPerro)
            {
                 EntityManagerFactory emf = Persistence.createEntityManagerFactory("EjercicioJPAPU"); 
                 EntityManager em = emf.createEntityManager();
                 return em.find(CPerro.class, codPerro);
            }
}
